

//
//  ZGSCartoonViewController.m
//  MapleLeaf
//
//  Created by dllo on 15/11/26.
//  Copyright © 2015年 AntennaBabyTeam. All rights reserved.
//

#import "ZGSCartoonViewController.h"

@interface ZGSCartoonViewController ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, strong) UIImageView *titileImageView;
@property(nonatomic, strong) UITableView *tableView;

@property(nonatomic, strong) ZGSCartoonfriendModel *friendModel;
@property(nonatomic, strong) ZGSCartoonfriendSonModel *sonFriendModel;

@property(nonatomic, assign) CGFloat picHeight;

@property(nonatomic, strong) NSMutableArray *refreshArr;

@property(nonatomic, assign) NSInteger page; // 加载page
@end


@implementation ZGSCartoonViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.barTintColor = NAVC_COLOR;
    self.navigationController.navigationBar.translucent = NO;
    
    
    // 设置navc图片
    self.titileImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10 * SCREEN_WIDTH / 375.0, 15, SCREEN_WIDTH / 4, 44)];
    [self.navigationController.view addSubview:self.titileImageView];
    self.titileImageView.image = [UIImage imageNamed:@"headImage.png"];
    
    // 这只navc标头
    self.navigationItem.title = @"漫友圈";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]}];
    
    // 创建tableView
    [self createTableView];
    
    
    // 下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(createData)];
    [self.tableView.mj_header beginRefreshing];
    
    // 上拉加载
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(createData)];
    
}

// 视图将要出现
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.titileImageView.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}


// 视图已经消失
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.titileImageView.hidden = YES;
}



#pragma mark 创建tableView
- (void)createTableView{
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    self.tableView.backgroundColor = [UIColor colorWithRed:0.9495 green:0.9495 blue:0.9495 alpha:1.0];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    // 关闭tableView线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //  注册cell
    [self.tableView registerClass:[ZGSCartoonFriendCell class] forCellReuseIdentifier:@"CartoonFriendCellReuseIdentifier"];
    self.page = 1;
    
}




#pragma mark - 数据解析
- (void)createData{
    if ([self.tableView.mj_header isRefreshing]) {
        [BaseAFN GETURLByString:@"http://api.youqudao.com/mhapi//api/feed/hot?customerId=1913463&page=1&size=20" AFNData:^(id result) {
            NSDictionary *dic = result;
            // 使用KVC方式赋值
            self.friendModel = [[ZGSCartoonfriendModel alloc] initWithDataSource:dic];
            
            self.refreshArr = [NSMutableArray array];
            for (NSInteger i = 0; i <self.friendModel.dataArray.count; i++) {
                [self.refreshArr addObject:@"NO"];
            }
            
            // 数据保护
            if (self.refreshArr.count > 0) {
                [self.tableView reloadData];
            }
            // 结束刷新
            [self.tableView.mj_header endRefreshing];
        }];
    }
    else if([self.tableView.mj_footer isRefreshing]){
        self.page++;
        
        [BaseAFN GETURLByString:[NSString stringWithFormat:@"http://api.youqudao.com/mhapi//api/feed/hot?customerId=1913463&page=%ld&size=20", self.page] AFNData:^(id result) {
            NSDictionary *dic = result;
            
            NSMutableArray *mArr = [NSMutableArray array];
            
            for (NSDictionary *tempDic in dic[@"data"][@"list"]) {
                ZGSCartoonfriendSonModel *model = [[ZGSCartoonfriendSonModel alloc] init];
                // 使用KVC的方法给小model赋值
                [model setValuesForKeysWithDictionary:tempDic];
                // 单独解析图片
                [model setValue:[[tempDic[@"pic"] componentsSeparatedByString:@","] objectAtIndex:0] forKey:@"pic"];
                // 添加
                [mArr addObject:model];
            }
            // 老数组接收新数组数组
            [self.friendModel.dataArray addObjectsFromArray:mArr];
            
            // 新建用于接收
            NSMutableArray *refreshMArr = [NSMutableArray arrayWithCapacity:0];
            for (NSInteger i = 0; i <self.friendModel.dataArray.count; i++) {
                [refreshMArr addObject:@"NO"];
            }
            [self.refreshArr addObjectsFromArray:refreshMArr];
            
            
            // 数据保护
            if (self.friendModel.dataArray.count > 0) {
                [self.tableView reloadData];
            }
            // 结束刷新
            [self.tableView.mj_footer endRefreshing];
        }];
    }
}



#pragma mark - tableView协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.friendModel.dataArray.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    // 从大model取值小model
    ZGSCartoonfriendSonModel *model = self.friendModel.dataArray[indexPath.row];
    
    ZGSCartoonFriendCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CartoonFriendCellReuseIdentifier"];
    // 关闭cell点击效果
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    // 设置cell颜色
    cell.backgroundColor = [UIColor colorWithRed:0.9495 green:0.9495 blue:0.9495 alpha:1.0];
    // 调用set方法赋值
    cell.friendSonModel = model;
    cell.picImageView.tag = 2000 + indexPath.row;

    
    
    
    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:@""] placeholderImage:[UIImage imageNamed:@""] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
    }];
    
    
    
    // cell 网络图片自适应
    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:model.pic] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        // 交叉相乘,不会因为图片放大而导致图片变质
        CGFloat picHeight = (SCREEN_WIDTH - 30) * image.size.height / image.size.width;
        
        // 创建图片自适应
        if (picHeight > 0) {
            // 背景view自适应frame
            cell.backView.frame = CGRectMake(5, 10, 365, picHeight + 155);
            // 自适应图片frame
            cell.picImageView.frame = CGRectMake(10, 115, 345, picHeight);
            // 头像
            cell.iconImageView.frame = CGRectMake(10, 5, 55, 55);
            // 网友姓名
            cell.nickNameLabel.frame = CGRectMake(70, 10, 100, 20);
            // 标题
            cell.contentLabel.frame = CGRectMake(10, 65, 345, 45);
            // 赞label
            cell.upConuntLabel.frame = CGRectMake(10, picHeight + 120, 70, 30);
            // 评论label
            cell.reCountLabel.frame = CGRectMake(85, picHeight + 120, 70, 30);
            // 点击次数label
            cell.readCountLabel.frame = CGRectMake(270, picHeight + 120, 85, 30);
        }
        else if(picHeight < 0){
            // 背景view自适应frame
            cell.backView.frame = CGRectMake(5, 10, 365, 345);
            // 占位图frame
            cell.picImageView.frame = CGRectMake(10, 115, 345, 200);
            // 头像
            cell.iconImageView.frame = CGRectMake(10, 5, 55, 55);
            // 网友姓名
            cell.nickNameLabel.frame = CGRectMake(70, 10, 100, 20);
            // 标题
            cell.contentLabel.frame = CGRectMake(10, 65, 345, 45);
            // 赞label
            cell.upConuntLabel.frame = CGRectMake(10, 315, 70, 30);
            // 评论label
            cell.reCountLabel.frame = CGRectMake(85, 315, 70, 30);
            // 点击次数label
            cell.readCountLabel.frame = CGRectMake(270, 315, 85, 30);
        }
        
        // 把得到的行高赋值到model里
        ZGSCartoonfriendSonModel *friendModel = self.friendModel.dataArray[indexPath.row];
        friendModel.picHeight = picHeight;
        
        if ([self.refreshArr[indexPath.row] isEqualToString:@"NO"]) {
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            
            self.refreshArr[indexPath.row] = @"YES";
        }
    }];
    
    return cell;
}




#pragma mark - tableView协议方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ZGSCartoonfriendSonModel *friendSonModel = self.friendModel.dataArray[indexPath.row];
    
    if (friendSonModel.picHeight) {
        return friendSonModel.picHeight + 170;
    }
    else{
        return 355;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ZGSCartoonfriendSonModel *model = self.friendModel.dataArray[indexPath.row];
    
    
    ZGSDetaileFriendController *zgsVC = [[ZGSDetaileFriendController alloc] init];
    [self.navigationController pushViewController:zgsVC animated:YES];
    
    zgsVC.mid = model.mid;
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
